import csv
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial.distance import cdist

with open('data1.csv') as csvFile:
    csvReader = csv.reader(csvFile, delimiter=",", quoting=csv.QUOTE_NONNUMERIC)
    data1 = []
    for row in csvReader:
        data1.append(row)
data1 = np.array(data1)

def k_means(X, k=2, max_iters=100, tol=1e-4):
    np.random.seed(np.random.randint(0, 10000))
    centroids = X[np.random.choice(len(X), k, replace=False)]
    for _ in range(max_iters):
        distances = cdist(X, centroids)
        labels = np.argmin(distances, axis=1)
        new_centroids = np.array([X[labels == i].mean(axis=0) for i in range(k)])
        if np.allclose(centroids, new_centroids, atol=tol):
            break
        centroids = new_centroids

    return labels, centroids

labels, centroids = k_means(data1, k=2)
colors = ['red', 'blue']
cluster_colors = [colors[label] for label in labels]

plt.figure(figsize=(8, 6))
plt.scatter(data1[:, 0], data1[:, 1], c=cluster_colors, label='Data Points')
plt.scatter(centroids[:, 0], centroids[:, 1], c=colors, marker='X', s=200, edgecolor='black', label='Centroids')
plt.title('K-Means Clustering on data1.csv (k=2)')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()